package api

import (
	"api-getaway/basic/global"
	"api-getaway/handler/request"
	"api-getaway/pkg"
	__ "api-getaway/proto"
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"net/http"
	"path/filepath"
)

func Create(c *gin.Context) {
	var req request.CreateReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"message": "验证失败",
			"code":    400,
			"data":    err.Error(),
		})
		return
	}

	goodnum := uuid.New().String()
	good, _ := global.GoodClient.CreateGood(c, &__.CreateGoodReq{
		Name:        req.Name,
		Picture:     req.Picture,
		GoodNum:     goodnum,
		GoodClassId: int64(req.GoodClassId),
		Inclue:      req.Incule,
		Number:      int64(req.Number),
		Price:       float32(req.Price),
	})

	c.JSON(http.StatusOK, gin.H{
		"message": "发布成功",
		"code":    200,
		"data":    good,
	})

}

func Onload(c *gin.Context) {
	file, _ := c.FormFile("file")

	uuid := uuid.NewString()
	filename := uuid + filepath.Ext(file.Filename)

	dst := "../api-getaway/staic/onload/" + filename
	// 上传文件至指定的完整文件路径
	c.SaveUploadedFile(file, dst)

	pkg.Onload(filename, dst)

	c.JSON(http.StatusOK, gin.H{
		"message": "图片上传成功",
		"code":    200,
		"data":    dst,
	})
}

func CreateAttribute(c *gin.Context) {
	var req request.CreateAttributeReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"message": "验证失败",
			"code":    400,
			"data":    err.Error(),
		})
		return
	}

	good, _ := global.GoodClient.CreateAttribute(c, &__.CreateAttributeReq{
		Name:   req.Name,
		GoodId: int64(req.GoodID),
	})

	c.JSON(http.StatusOK, gin.H{
		"message": "发布成功",
		"code":    200,
		"data":    good,
	})

}

func Value(c *gin.Context) {
	var req request.CreateValueReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"message": "验证失败",
			"code":    400,
			"data":    err.Error(),
		})
		return
	}

	good, _ := global.GoodClient.CreateValue(c, &__.CreateValueReq{
		Name:        req.Name,
		AttributeId: int64(req.AttributeId),
	})

	c.JSON(http.StatusOK, gin.H{
		"message": "发布成功",
		"code":    200,
		"data":    good,
	})
}

func List(c *gin.Context) {
	var req request.ListReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"message": "验证失败",
			"code":    400,
			"data":    err.Error(),
		})
		return
	}

	good, _ := global.GoodClient.ListGood(c, &__.ListGoodReq{
		Page:   req.Page,
		Size:   req.Size,
		Name:   req.Name,
		Number: int64(req.Number),
	})

	c.JSON(http.StatusOK, gin.H{
		"message": "展示成功",
		"code":    200,
		"data":    good,
	})

}
